#include "speech.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>


Speech::Speech(QObject *parent) : QObject(parent)
{

}

QString Speech::speechIdentify(QString fileName)
{
    //获取access_token
    QString tokenUrl=QString(baiduTokenUrl).arg(client_id).arg(client_secret);

    QMap<QString,QString> header;
    header.insert(QString("Content-Type"),QString("audio/pcm;tate=16000"));

    QByteArray requestData;
    QByteArray replyData;

    Http m_http;
    bool result= m_http.post_sync(tokenUrl,header,requestData,replyData);

    QString accessToken;
    if(result)
    {
        QString key="access_token";
        accessToken=getJsonValue(replyData,key);
        qDebug()<<accessToken;
    }
    else {
        qDebug()<<"发送请求获取token失败";
    }
    replyData.clear();


    //组合url
    QString speechurl=QString(speechUrl).arg(QHostInfo::localHostName()).arg(accessToken);

    //把文件转成QBytearry
    QFile file;
    file.setFileName(fileName);
    file.open(QIODevice::ReadOnly);
    requestData=file.readAll();
    file.close();
    //再次发起请求 进行识别
    bool result1= m_http.post_sync(speechurl,header,requestData,replyData);
    if(result1)
    {
        QString key="result";
        QString text=getJsonValue(replyData,key);
        qDebug()<<text;
        return  text;
    }
    else {
        qDebug()<<"识别失败";
    }
}

QString Speech::getJsonValue(QByteArray ba, QString key)
{
    QJsonDocument jsonDocument=QJsonDocument::fromJson(ba);
    QJsonObject jsonObject =jsonDocument.object();
    if(jsonObject.contains(key)){
        QJsonValue jsonVal=jsonObject.value(key);
        if(jsonVal.isString())
        {
            return jsonVal.toString();
        }
        else if (jsonVal.isArray()) {
            QJsonArray arr=jsonVal.toArray();
            QJsonValue jv=arr.at(0);
            return jv.toString();
        }
    }
    else {
        return "";
    }
}
